package com.zzh.jetpackdemo.room

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import com.zzh.jetpackdemo.R
import com.zzh.jetpackdemo.room.base.AppDatabase
import com.zzh.jetpackdemo.room.data.User
import kotlinx.android.synthetic.main.activity_room.*

class RoomActivity : AppCompatActivity() {

    lateinit var appDaoBase: AppDatabase
    var mUser: User? = null
    var mUsers: List<User>? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_room)
        appDaoBase = AppDatabase.newInstance(this)
        setClick()
    }


    private fun setClick() {
        insertUser.setOnClickListener {
            var id = appDaoBase.getUserDao().insert(User("zhangzhihao", 12, 21))
            Log.i("zhangzhihao", "insertUser${id}")
        }
        insertUsers.setOnClickListener {
            var users = arrayOf(
                User("zhangzhihao1", 1, 1 + 12),
                User("zhangzhihao2", 2, 2 + 12),
                User("zhangzhihao3", 3, 3 + 12),
                User("zhangzhihao4", 4, 4 + 12),
                User("zhangzhihao5", 5, 5 + 12),
                User("zhangzhihao6", 6, 6 + 12),
                User("zhangzhihao7", 7, 7 + 12),
                User("zhangzhihao8", 8, 8 + 12),
                User("zhangzhihao9", 9, 9 + 12),
                User("zhangzhihao11", 11, 11 + 12)
            )
            appDaoBase.getUserDao().insertAll(*users)
            Log.i("zhangzhihao", "insertUsers")
        }
        deleta.setOnClickListener {
            mUser?.let {
                appDaoBase.getUserDao().delete(it)
                mUser = null
                Log.i("zhangzhihao", "deleta")
            }
            Log.i("zhangzhihao", "deleta")
        }
        deletaAll.setOnClickListener {
            mUsers?.let {
                var users = it.toTypedArray()
                appDaoBase.getUserDao().deletaAll(*users)
                mUsers = null
                Log.i("zhangzhihao", "deletaAll")
            }
            Log.i("zhangzhihao", "deletaAll")
        }
        update.setOnClickListener {
            mUser?.let {
                it.name = "update${it.name}"
                appDaoBase.getUserDao().update(it)
                Log.i("zhangzhihao", "update")
                mUser = null
            }
            Log.i("zhangzhihao", "update")
        }
        loadUsers.setOnClickListener {
            mUsers = appDaoBase.getUserDao().loadUsers()
            mUsers?.let {
                if (it.isNotEmpty()) {
                    mUser = it[0]
                }
            }
            value.text = mUsers.toString()
        }
        loadUser.setOnClickListener {
            mUser = appDaoBase.getUserDao().loadUser(3)
            value.text = mUser.toString()
        }
    }

}